package com.resource.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * httpLog记录
 * @author Tao.yu
 * @version v3.0
 * @date 2019/12/9 17:30
 **/
@Slf4j
public class TrackLogClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
	@Override
	public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
		trackRequest(httpRequest,bytes);
		ClientHttpResponse httpResponse = clientHttpRequestExecution.execute(httpRequest,bytes);
		trackResponse(httpResponse);
		return httpResponse;
	}

	private void trackResponse(ClientHttpResponse httpResponse)throws IOException {
		log.info("============================response begin==========================================");
		log.info("Status code  : {}", httpResponse.getStatusCode());
		log.info("Status text  : {}", httpResponse.getStatusText());
		log.info("Headers      : {}", httpResponse.getHeaders());
		log.info("=======================response end=================================================");
	}

	private void trackRequest(HttpRequest request, byte[] body)throws UnsupportedEncodingException {
		log.info("======= request begin ========");
		log.info("uri : {}", request.getURI());
		log.info("method : {}", request.getMethod());
		log.info("headers : {}", request.getHeaders());
		log.info("request body : {}", new String(body, StandardCharsets.UTF_8));
		log.info("======= request end ========");
	}
}
